package com.by.service.impl;

import com.by.common.crud.BaseServiceImpl;
import com.by.dao.DeptDao;
import com.by.entity.Dept;
import com.by.query.DeptQuery;
import com.by.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

@Service
public class DeptServiceImpl extends BaseServiceImpl<Dept, DeptDao> implements DeptService {
    @Autowired
    private DeptDao deptDao;

    /*
     * 重写新增方法
     * */
    @Override
    public int save(Dept entity) {
        entity.setDeptCode(generateDeptCode(entity.getParentId()));
        return super.save(entity);
    }

    /*
    * 生成最大编码
    * */
    String generateDeptCode(int parentId) {
//  根据父id查询最大编码(最新编码)
        String maxCode = baseMapper.queryMaxCode(parentId);
        //不存在最大编码就创建
        if (null == maxCode) {
            if (parentId == 0) {
                return "101";
            }
            //根据夫id查询编码
            String parentCode = baseMapper.queryCodeById(parentId);
            return parentCode + "01";
        }
        //如果存在最大编码原基础加一
        Integer tmp=Integer.parseInt(maxCode);
        tmp++;
        return String.valueOf(tmp);
    }
    /*
    * 重写删除方法
    * */
    @Override
    public int delete(Serializable id) {
        //查询子部门
        int n=baseMapper.queryChildCount(id);
        if(n>0){//说明有子部门不让删除
            return 2;
        }
        return super.delete(id);

    }

    @Override
    public int updateStatus(int id, int status) {
        return baseMapper.updateStatus(id, status);
    }

    @Override
    public String queryByName(String name) {
        return baseMapper.queryByName(name);
    }

    @Override
    public List<Map> queryChildDept(DeptQuery query) {
        return baseMapper.queryChildDept(query);
    }

    @Override
    public List queryTree(int parentId) {
        List list = baseMapper.queryTree(parentId);
        return list;
    }
}
